import React, { useState, useEffect, useRef } from 'react';
import './index.css';

const Index: React.FC = () => {
  // 密码状态管理
  const [password, setPassword] = useState<string[]>(['', '', '', '']);
  const [currentDigit, setCurrentDigit] = useState<number>(0);
  const [attemptsLeft, setAttemptsLeft] = useState<number>(3);
  const [isLocked, setIsLocked] = useState<boolean>(true);
  const [isUnlocked, setIsUnlocked] = useState<boolean>(false);
  const [notification, setNotification] = useState<{
    message: string;
    type: 'success' | 'error' | '';
  }>({ message: '', type: '' });
  const [showHint, setShowHint] = useState<boolean>(false);
  
  // 门动画状态
  const [doorsOpen, setDoorsOpen] = useState<boolean>(false);
  const [hingeSoundPlayed, setHingeSoundPlayed] = useState<boolean>(false);
  
  // 音效引用
  const buttonSoundRef = useRef<HTMLAudioElement>(null);
  const successSoundRef = useRef<HTMLAudioElement>(null);
  const errorSoundRef = useRef<HTMLAudioElement>(null);
  const hingeSoundRef = useRef<HTMLAudioElement>(null);
  
  // 正确密码 - 故宫建成年份
  const CORRECT_PASSWORD = ['1', '4', '2', '0'];
  
  // 处理数字输入
  const handleDigitPress = (digit: string) => {
    if (currentDigit < 4 && isLocked && !doorsOpen) {
      playSound(buttonSoundRef);
      const newPassword = [...password];
      newPassword[currentDigit] = digit;
      setPassword(newPassword);
      setCurrentDigit(currentDigit + 1);
    }
  };
  
  // 删除最后一位
  const handleDelete = () => {
    if (currentDigit > 0 && isLocked && !doorsOpen) {
      playSound(buttonSoundRef);
      const newPassword = [...password];
      newPassword[currentDigit - 1] = '';
      setPassword(newPassword);
      setCurrentDigit(currentDigit - 1);
    }
  };
  
  // 提交密码
  const handleSubmit = () => {
    if (currentDigit === 4 && isLocked && !doorsOpen) {
      playSound(buttonSoundRef);
      
      if (password.join('') === CORRECT_PASSWORD.join('')) {
        // 密码正确
        setNotification({ message: '密码正确！', type: 'success' });
        playSound(successSoundRef);
        setIsUnlocked(true);
        setIsLocked(false);
        setTimeout(() => {
          setDoorsOpen(true);
        }, 1000);
      } else {
        // 密码错误
        const newAttempts = attemptsLeft - 1;
        setAttemptsLeft(newAttempts);
        setNotification({ 
          message: `密码错误！还剩${newAttempts}次尝试`, 
          type: 'error' 
        });
        playSound(errorSoundRef);
        
        // 清空密码
        setTimeout(() => {
          setPassword(['', '', '', '']);
          setCurrentDigit(0);
        }, 1000);
        
        // 锁定
        if (newAttempts === 0) {
          setIsLocked(true);
        }
      }
      
      // 清除通知
      setTimeout(() => {
        setNotification({ message: '', type: '' });
      }, 2000);
    }
  };
  
  // 重置游戏
  const resetGame = () => {
    setPassword(['', '', '', '']);
    setCurrentDigit(0);
    setAttemptsLeft(3);
    setIsLocked(true);
    setIsUnlocked(false);
    setDoorsOpen(false);
    setHingeSoundPlayed(false);
    setNotification({ message: '', type: '' });
    setShowHint(false);
  };
  
  // 播放音效
  const playSound = (soundRef: React.RefObject<HTMLAudioElement>) => {
    if (soundRef.current) {
      soundRef.current.currentTime = 0;
      soundRef.current.play().catch(e => console.log('音效播放失败:', e));
    }
  };
  
  // 门打开时播放铰链音效
  useEffect(() => {
    if (doorsOpen && !hingeSoundPlayed) {
      playSound(hingeSoundRef);
      setHingeSoundPlayed(true);
    }
  }, [doorsOpen, hingeSoundPlayed]);
  
  // 键盘支持
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key >= '0' && e.key <= '9') {
        handleDigitPress(e.key);
      } else if (e.key === 'Backspace') {
        handleDelete();
      } else if (e.key === 'Enter') {
        handleSubmit();
      }
    };
    
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [password, currentDigit, isLocked, doorsOpen]);

  return (
    <div className="app-container">
      {/* 音效元素 - 不可见 */}
      <audio ref={buttonSoundRef} preload="auto">
        <source src="https://assets.mixkit.co/sfx/preview/mixkit-interface-button-click-1109.mp3" type="audio/mpeg" />
      </audio>
      <audio ref={successSoundRef} preload="auto">
        <source src="https://assets.mixkit.co/sfx/preview/mixkit-unlocking-563.mp3" type="audio/mpeg" />
      </audio>
      <audio ref={errorSoundRef} preload="auto">
        <source src="https://assets.mixkit.co/sfx/preview/mixkit-wrong-answer-fail-notification-946.mp3" type="audio/mpeg" />
      </audio>
      <audio ref={hingeSoundRef} preload="auto">
        <source src="https://assets.mixkit.co/sfx/preview/mixkit-old-wooden-door-creaking-open-2754.mp3" type="audio/mpeg" />
      </audio>
      
      <h1>故宫密室 - 宫门密码锁</h1>
      
      <div className="game-info">
        <p>你发现了一扇古老的故宫宫门，上面有一个密码锁。解开密码才能进入下一个区域。</p>
        <p className="attempts-left">剩余尝试次数: {attemptsLeft}</p>
        <button 
          className="hint-btn" 
          onClick={() => setShowHint(!showHint)}
        >
          {showHint ? '隐藏提示' : '查看提示'}
        </button>
        {showHint && (
          <div className="hint">
            提示：这扇门见证了历史的开端，密码是它诞生的年份
          </div>
        )}
      </div>
      
      <div className="door-frame">
        {/* 门后场景图片 */}
        <div className="behind-door-scene">
          <img 
            src="https://picsum.photos/id/1036/1200/800" 
            alt="故宫内部景象" 
            className="behind-door-image"
          />
        </div>
        
        {/* 左门 */}
        <div className={`door left-door ${doorsOpen ? 'open-left' : ''}`}>
          <div className="door-texture"></div>
          <div className="door-hinges">
            <div className="hinge-pin"></div>
            <div className="hinge-pin"></div>
          </div>
          <div className="door-decoration top-left"></div>
          <div className="door-decoration bottom-left"></div>
        </div>
        
        {/* 右门 */}
        <div className={`door right-door ${doorsOpen ? 'open-right' : ''}`}>
          <div className="door-texture"></div>
          <div className="door-hinges right-hinges">
            <div className="hinge-pin"></div>
            <div className="hinge-pin"></div>
          </div>
          <div className="door-decoration top-right"></div>
          <div className="door-decoration bottom-right"></div>
        </div>
        
        {/* 密码锁 */}
        {isLocked && !isUnlocked && (
          <div className={`lock-container ${notification.type === 'error' ? 'shake' : ''}`}>
            {notification.message && (
              <div className={`notification ${notification.type}`}>
                {notification.message}
              </div>
            )}
            
            <div className="password-display">
              {password.map((digit, index) => (
                <div 
                  key={index} 
                  className={`digit-box ${index === currentDigit ? 'active' : ''}`}
                >
                  {digit}
                </div>
              ))}
            </div>
            
            <div className="keypad">
              <div className="keypad-row">
                <button className="digit-btn" onClick={() => handleDigitPress('1')}>1</button>
                <button className="digit-btn" onClick={() => handleDigitPress('2')}>2</button>
                <button className="digit-btn" onClick={() => handleDigitPress('3')}>3</button>
              </div>
              <div className="keypad-row">
                <button className="digit-btn" onClick={() => handleDigitPress('4')}>4</button>
                <button className="digit-btn" onClick={() => handleDigitPress('5')}>5</button>
                <button className="digit-btn" onClick={() => handleDigitPress('6')}>6</button>
              </div>
              <div className="keypad-row">
                <button className="digit-btn" onClick={() => handleDigitPress('7')}>7</button>
                <button className="digit-btn" onClick={() => handleDigitPress('8')}>8</button>
                <button className="digit-btn" onClick={() => handleDigitPress('9')}>9</button>
              </div>
              <div className="keypad-row">
                <button className="func-btn delete-btn" onClick={handleDelete}>删除</button>
                <button className="digit-btn" onClick={() => handleDigitPress('0')}>0</button>
                <button className="func-btn submit-btn" onClick={handleSubmit}>确认</button>
              </div>
            </div>
          </div>
        )}
      </div>
      
      {/* 结果提示 */}
      {!isLocked && isUnlocked && doorsOpen && (
        <div className="unlocked-message">
          <p>恭喜！你成功打开了故宫大门，发现了隐藏的秘密！</p>
          <button className="reset-btn" onClick={resetGame}>重新开始</button>
        </div>
      )}
      
      {isLocked && attemptsLeft === 0 && (
        <div className="locked-message">
          <p>密码已锁定，请重试。</p>
          <button className="reset-btn" onClick={resetGame}>重新开始</button>
        </div>
      )}
    </div>
  );
};

export default Index;
